package com.movie.controller;

import com.movie.entity.Movie;
import com.movie.service.MovieService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/movies") // 基础路径
@CrossOrigin(origins = "http://localhost:5173") // 确保允许前端访问
public class MovieController {

    @Autowired
    private MovieService movieService;

    // 获取所有电影，或按标题、导演、状态搜索
    @GetMapping
    public ResponseEntity<List<Movie>> getMovies(
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String director,
            @RequestParam(required = false) String status) {
        
        List<Movie> movies;
        // 如果有任何搜索条件，则调用搜索服务
        if ((title != null && !title.isEmpty()) || 
            (director != null && !director.isEmpty()) || 
            (status != null && !status.isEmpty())) {
            movies = movieService.searchMovies(title, director, status); 
        } else {
            // 否则获取所有电影
            movies = movieService.getAllMovies();
        }
        return ResponseEntity.ok(movies);
    }

    // 获取即将上映的电影
    @GetMapping("/upcoming")
    public ResponseEntity<List<Movie>> getUpcomingMovies() {
        // 假设 "UPCOMING" 是表示即将上映的状态字符串
        List<Movie> movies = movieService.getMoviesByStatus("UPCOMING");
        return ResponseEntity.ok(movies);
    }

    // 获取单个电影详情
    @GetMapping("/{id}")
    public ResponseEntity<Movie> getMovieById(@PathVariable Long id) {
        Movie movie = movieService.getMovieById(id);
        if (movie != null) {
            return ResponseEntity.ok(movie);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // --- 以下接口通常需要管理员权限 --- 这部分接口已移至 AdminMovieController

    // // 添加电影
    // @PostMapping
    // public ResponseEntity<Movie> addMovie(@RequestBody Movie movie) {
    //     // 需要权限校验
    //     Movie addedMovie = movieService.addMovie(movie);
    //     return ResponseEntity.ok(addedMovie);
    // }

    // // 更新电影
    // @PutMapping("/{id}")
    // public ResponseEntity<Movie> updateMovie(@PathVariable Long id, @RequestBody Movie movie) {
    //     // 需要权限校验
    //     movie.setId(id); // 确保 ID 正确
    //     Movie updatedMovie = movieService.updateMovie(movie);
    //     if (updatedMovie != null) {
    //         return ResponseEntity.ok(updatedMovie);
    //     } else {
    //         return ResponseEntity.notFound().build();
    //     }
    // }

    // // 删除电影
    // @DeleteMapping("/{id}")
    // public ResponseEntity<?> deleteMovie(@PathVariable Long id) {
    //     // 需要权限校验
    //     boolean deleted = movieService.deleteMovie(id);
    //     if (deleted) {
    //         return ResponseEntity.ok("Movie deleted successfully");
    //     } else {
    //         return ResponseEntity.notFound().build();
    //     }
    // }
} 